<?php
declare (strict_types=1);

namespace app\user\logic\user\admin;

use app\common\exception\LogicException;
use app\user\model\user\admin\Balance as BalanceModel;

/**
 * 账户余额接口类
 */
class Balance extends BalanceModel
{

    // /**
    //  * 获取账户余额信息
    //  * Author   亓官雨树<lucky.max@foxmail.com>
    //  * Date 2020-04-21
    //  *
    //  * @return   [type]                      [description]
    //  */
    // public function getUserBalanceInfo()
    // {
    //     $info = $this->where('user_id', request()->mid)->findOrEmpty();
    //
    //     return $info ?? new \ArrayObject();
    // }
    //
    // /**
    //  * 获取用户余额
    //  * Author   亓官雨树<lucky.max@foxmail.com>
    //  * Date 2020-05-06
    //  */
    // public function userBalance()
    // {
    //     $balance = $this->scope('userBalance')->value('balance');
    //
    //     return $balance;
    // }

    /**
     * 变更用户余额信息
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-04-21
     *
     * @return   [type]                      [description]
     */
    public function updateUserBalance($param)
    {
        // 验证数据
        $this->getValidate()->scene('update')->failException()->check($param);
        $type = $param['type'];
        $num  = $param['num'];
        $uid  = request()->mid;

        $balance = new \ArrayObject();
        $fun     = $type . 'UserBalance';

        if (method_exists($this, $fun)) {
            $balance = $this->$fun($uid, $num);
        }

        return $balance;
    }

    /**
     * 系统增加余额
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-04-21
     */
    public function increaseUserBalance($uid, $num)
    {
        $this->startTrans();
        try {
            $balance = $this->where('user_id', $uid)->findOrEmpty();
            if ($balance->isEmpty()) {
                // 添加余额
                $balance          = new Balance;
                $balance->user_id = $uid;
                $balance->balance = $num;
                if (!$balance->save()) {
                    throw new LogicException('用户余额变更失败');
                }
            } else {
                // 变更余额
                $balance->balance += $num;
                $balance->save();
            }
            // 流水记录
            app(BalanceFlow::class)->updateFlow($uid, 14, $num, $balance->balance, 0, 0, '系统增加');
            $this->commit();
        } catch (LogicException $e) {
            $this->rollback();
            throw new LogicException('用户余额变更失败');
        }

        return $balance;
    }

    /**
     * 系统扣除余额
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-04-21
     */
    public function decreaseUserBalance($uid, $num)
    {
        $this->startTrans();
        try {
            $info = $this->where('user_id', $uid)->findOrEmpty();
            // 余额不足
            if ($info->isEmpty() || $info->balance < $num) {
                throw new LogicException('当前用户余额不足');
            }
            // 变更余额
            $info->balance -= $num;
            $info->save();
            $balance = $this->find($info->id);
            // 流水记录
            app(BalanceFlow::class)->updateFlow($uid, 15, $num, $info->balance, 0, 0, '系统扣除');
            $this->commit();
        } catch (LogicException $e) {
            $this->rollback();
            throw new LogicException($e->getMessage());
        }

        return $balance;
    }

    /**
     * 设置用户余额
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/9/8
     *
     * @param int $userId
     * @param     $balance
     * @return Balance|array|\think\Model|null
     */
    public function setUserBalance(int $userId, $balance)
    {
        $data = $this->where('user_id', $userId)->findOrEmpty();
        if ($data->isEmpty() || $data->balance < $balance) {
            $num = $balance - $data->balance;
            return $this->increaseUserBalance($userId, $num);
        } else if ($data->balance > $balance) {
            $num = $data->balance - $balance;
            return $this->decreaseUserBalance($userId, $num);
        }

        throw new LogicException('未做任何操作');
    }

}
